<template>
  <section class="page cart-page">
    <h1 class="page-title">购物车</h1>

    <div class="card">
      <div class="card-body">
        <div v-if="loading" class="text-muted">购物车加载中...</div>
        <div v-else>
          <div class="table-responsive">
            <el-table :data="cart" stripe style="width: 100%" empty-text="购物车为空">
              <el-table-column label="商品" min-width="260">
                <template #default="{ row }">
                  <div class="d-flex align-items-center">
                    <el-image :src="row.cover" alt="cover" style="width: 64px; height: 64px" class="me-2" fit="cover" />
                    <div>
                      <div class="fw-bold">{{ row.name }}</div>
                      <el-text type="info" size="small">{{ row.categoryName }}</el-text>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="单价" width="120" align="center">
                <template #default="{ row }">¥ {{ row.price.toFixed(2) }}</template>
              </el-table-column>
              <el-table-column label="数量" width="200" align="center">
                <template #default="{ row }">
                  <el-input-number v-model="row.count" :min="1" @change="() => {}" />
                </template>
              </el-table-column>
              <el-table-column label="小计" width="140" align="center">
                <template #default="{ row }">¥ {{ (row.price * row.count).toFixed(2) }}</template>
              </el-table-column>
              <el-table-column label="操作" width="140" align="center">
                <template #default="{ row }">
                  <el-button size="small" type="danger" @click="remove(row)">移除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="d-flex justify-content-between align-items-center mt-3">
            <div class="text-muted">共 {{ totalItems }} 件商品</div>
            <div class="h5 mb-0">
              应付总额：<span class="text-danger">¥ {{ totalAmount.toFixed(2) }}</span>
            </div>
          </div>

          <div class="mt-3 d-flex gap-2">
            <button class="btn btn-outline-secondary" @click="clear">清空购物车</button>
            <button class="btn btn-primary" @click="checkout" :disabled="cart.length === 0 || checking">
              {{ checking ? "结算中..." : "去结算" }}
            </button>
          </div>

          <div v-if="msg" class="alert alert-success mt-2">{{ msg }}</div>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
// 模拟购物车接口：增减数量、移除、清空、结算
import { ref, computed, onMounted } from "vue";

interface CartItem {
  id: string;
  name: string;
  categoryName: string;
  price: number;
  cover: string;
  count: number;
}

const loading = ref(false);
const checking = ref(false);
const cart = ref<CartItem[]>([]);
const msg = ref("");

function mockFetchCart(): Promise<CartItem[]> {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([
        {
          id: "p_1",
          name: "示例产品 1",
          categoryName: "数码",
          price: 199,
          cover: "https://picsum.photos/seed/cart1/64/64",
          count: 1,
        },
        {
          id: "p_2",
          name: "示例产品 2",
          categoryName: "图书",
          price: 59,
          cover: "https://picsum.photos/seed/cart2/64/64",
          count: 2,
        },
        {
          id: "p_3",
          name: "示例产品 3",
          categoryName: "玩具",
          price: 89,
          cover: "https://picsum.photos/seed/cart3/64/64",
          count: 1,
        },
      ]);
    }, 500);
  });
}

function mockCheckout(payload: CartItem[]): Promise<{ orderId: string }> {
  return new Promise((resolve) => setTimeout(() => resolve({ orderId: "ORD-20250930-0001" }), 1000));
}

const totalItems = computed(() => cart.value.reduce((sum, it) => sum + it.count, 0));
const totalAmount = computed(() => cart.value.reduce((sum, it) => sum + it.count * it.price, 0));

function inc(it: CartItem) {
  it.count++;
}
function dec(it: CartItem) {
  it.count = Math.max(1, it.count - 1);
}
function remove(it: CartItem) {
  cart.value = cart.value.filter((x) => x.id !== it.id);
}
function clear() {
  cart.value = [];
}
async function checkout() {
  checking.value = true;
  msg.value = "";
  const res = await mockCheckout(cart.value);
  checking.value = false;
  msg.value = `结算成功（模拟后端），订单号：${res.orderId}`;
  clear();
}

async function load() {
  loading.value = true;
  cart.value = await mockFetchCart();
  loading.value = false;
}

onMounted(load);
</script>

<style scoped lang="scss">
.page {
  padding: 16px;
}
.page-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 8px;
}
</style>
